package com.victor9ac;


import java.io.IOException;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
import spark.servlet.SparkApplication;


public class SparkFreemarketWeb implements SparkApplication {

	MongoDB mongoDB;
	
	
	
	
	public SparkFreemarketWeb() {
		super();
		this.mongoDB = MongoDB.getInstance();
	}




	public void init() {
		
        final Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(
        		SparkFreemarketWeb.class, "/");
		
		
		Spark.get(new Route("/hello") {
			@Override
			public Object handle(Request request, Response response) {
				
				StringWriter stringWriter = new StringWriter();
				
				try {		
					
					String a = mongoDB.getOneAtributteA();
                    try {
                    	
						Template myTemplate = configuration.getTemplate("hello.ftl");
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("name", "Anneta_"+a);						
						myTemplate.process(map, stringWriter);
			
						
					} catch (IOException e) {
						e.printStackTrace();
					} catch (TemplateException e) {
						e.printStackTrace();
					}
                    					
					
					
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				
                return stringWriter;
			}
		});
		
		
		Spark.get(new Route("/") {
			@Override
			public Object handle(Request request, Response response) {
				response.redirect("/hello");
				return null;
			}
		});

		Spark.get(new Route("/hello/:name") {
			@Override
			public Object handle(Request request, Response response) {
				return  String.format("Hello, %s!", request.params(":name"));
			}
		});
	}
	
}
